package com.LeeCode;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * 不间断子数组
 */

public class Code2762 {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 1};
        System.out.println(new Code2762().continuousSubarrays(nums));
    }

    public long continuousSubarrays(int[] nums) {
        Deque<Integer> maxQue = new ArrayDeque<>();
        Deque<Integer> minQue = new ArrayDeque<>();
        long ans = 0;
        int left = 0;
        for (int right = 0; right < nums.length; right++) {
            while (!maxQue.isEmpty() && nums[maxQue.getLast()] <= nums[right]) {
                maxQue.removeLast();
            }
            maxQue.addLast(right);

            while (!minQue.isEmpty() && nums[minQue.getLast()] >= nums[right]) {
                minQue.removeLast();
            }
            minQue.addLast(right);

            while (Math.abs(nums[maxQue.getFirst()] - nums[minQue.getFirst()]) > 2) {
                if (maxQue.getFirst() <= left)
                    maxQue.removeFirst();

                if (minQue.getFirst() <= left)
                    minQue.removeFirst();

                left++;
            }

            ans += right - left + 1;
        }
        return ans;
    }
}
